package com.treetao.union.web.task;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import com.treetao.union.db.Const.OrderRecord;
import com.treetao.union.db.Const.OrderStatus;
import com.treetao.union.db.SettingConvertService;
import com.treetao.union.db.model.MallOrder;
import com.treetao.union.db.pojo.SettingTypeOrder;
import com.treetao.union.db.service.MallOrderService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration      //1.主要用于标记配置类
@EnableScheduling   // 2.开启定时任务
public class OrderScheduleTask {
	@Autowired
	private SettingConvertService settingConvertService;
	@Autowired
	private MallOrderService mallOrderService;

	/**
	 * 扫描自动取消订单（下单后几小时未支付）
	 * */
//	@Scheduled(cron = "*/10 * * * * ?") //每10秒执行一次
	@Scheduled(cron = "0 0/1 * * * ?")//每2分钟
	public void executeAutoCancle() {
		log.info("1分钟执行一次超时支付订单扫描...");
		SettingTypeOrder setting = settingConvertService.getOrderSetting();
		if(setting.getOrderAutoCancleHour()==null) {
			log.warn("扫描超时未支付订单，请设置订单超时时间");
		}
		List<MallOrder> list = mallOrderService.getOrderListAtferCreate(setting.getOrderAutoCancleHour());
		if(list!=null && list.size()>0) {
			list.forEach(item->{
				mallOrderService.changeOrderStatus(item.getOrderno(), OrderStatus.CANCLE_SYSTEM, OrderRecord.CANCLE);
			});
		}
	}
	
	/**
	 * 扫描订单自动收货（发货后几天未确认收货）
	 * */
	@Scheduled(cron = "0 0/30 * * * ?") //每30分钟执行一次
	public void executeAutoReceive() {
		log.info("5分钟执行一次超时未确认收货订单扫描...");
		SettingTypeOrder setting = settingConvertService.getOrderSetting();
		if(setting.getOrderAutoReceiveDay()==null) {
			log.warn("扫描超时未支付订单，请设置订单超时时间");
		}
		List<MallOrder> list = mallOrderService.getOrderListAtferSend(setting.getOrderAutoReceiveDay());
		if(list!=null && list.size()>0) {
			list.forEach(item->{
				mallOrderService.changeOrderStatus(item.getOrderno(), OrderStatus.RECEIVED_SYSTEM, OrderRecord.RECEIVED);
			});
		}
	}
}
